package com.codemonkey.lq.qd.utils;

import org.apache.ibatis.io.Resources;

public class ClassHelper {
	/**
	 * 获取指定类的相对ClassLoader的路径; 用途嘛,例如用于获取与类处于同一package下的资源文件
	 * @param cls
	 * @return
	 */
	public static String getClassPath(final Class<?> cls) {
		// cls.getName()
		final String fullName = cls.getName();
		int lastIndexOfDot = fullName.lastIndexOf(".");
		return fullName.substring(0, lastIndexOfDot).replace('.', '/');
	}

	/**
	 * 
	 * @param cls
	 * @return
	 * @see cn.hutool.core.util.ReflectUtil.newInstance
	 */
	@SuppressWarnings("unchecked")
	public static <T> T newInstance(Class<?> cls) {
		if (null == cls) {
			return null;
		}

		Object instance = null;
		Exception ex = null;
		try {
			instance = cls.newInstance();
		} catch (InstantiationException e) {
			ex = e;
		} catch (IllegalAccessException e) {
			ex = e;
		}

		if (null == instance && null != ex) {
			String errorInfoString = String.format("can not instance the class [ %s ]", cls
					.getName());
			throw new IllegalArgumentException(errorInfoString, ex);
		}

		return (T) instance;
	}

	public static <T> T newInstance(String className) {
		Class<?> cls;
		try {
			cls = Resources.classForName(className);
			return ClassHelper.<T> newInstance(cls);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}

}
